package br.com.affero.util;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.ServletContext;

import org.apache.struts.upload.FormFile;

public class UploadedFile {

	public static String save(ServletContext context, FormFile formFile, String local) throws Exception {
		if (formFile.getFileName().length() > 0) {
			String path = context.getRealPath(local);
			String separator = System.getProperty("file.separator");
			String filePath = String.format("%s%s%s", path, separator, formFile.getFileName());

			// TODO: E se o arquivo existir? Qual politica adotar?
			File file = new File(filePath);
			
			// Escrevendo o arquivo.
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(file);
				out.write(formFile.getFileData());
			} finally {
				out.close();
			}
			
			return filePath;
		}
		
		return null;
	}

	public static boolean delete(String filePath) {
		return new File(filePath).delete();
	}
	
}
